<template>
  <div class="warehouse-detail">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/warehouse' }">仓库管理</el-breadcrumb-item>
      <el-breadcrumb-item>仓库详情</el-breadcrumb-item>
    </el-breadcrumb>

    <div v-loading="loading" class="detail-container">
      <!-- 仓库标题和操作按钮 -->
      <div class="detail-header">
        <h2>{{ warehouse.name || '' }}({{ warehouse.code || '' }})</h2>
        <div class="action-buttons">
          <el-button type="primary" @click="handleEdit">编辑</el-button>
          <el-button type="danger" @click="handleDelete">删除</el-button>
          <el-button :type="warehouse.status === 1 ? 'warning' : 'success'" @click="toggleStatus">
            {{ warehouse.status === 1 ? '停用' : '启用' }}
          </el-button>
          <el-button type="info" @click="toggleLock">
            {{ warehouse.isQuitLocked ? '解锁' : '锁定' }}
          </el-button>
          <el-button @click="handlePrint">打印</el-button>
        </div>
      </div>

      <!-- 仓库详细信息 -->
      <el-card class="info-card">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="提交人">{{ warehouse.creator || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="操作时间">{{ warehouse.createTime || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ warehouse.updateTime || '未知' }}</el-descriptions-item>

          <el-descriptions-item label="仓库编号">{{ warehouse.code || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="仓库名称">{{ warehouse.name || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="仓库容量/m³">{{ warehouse.area || 0 }}</el-descriptions-item>

          <el-descriptions-item label="库管部门">{{ warehouse.department || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="仓库主管">{{ warehouse.manager || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ warehouse.contactPhone || '未知' }}</el-descriptions-item>

          <el-descriptions-item label="仓库地址" :span="3">{{ warehouse.address || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="3">{{ warehouse.description || '无' }}</el-descriptions-item>
          
          <el-descriptions-item label="状态">
            <el-tag :type="warehouse.status === 1 ? 'success' : 'danger'">
              {{ warehouse.status === 1 ? '启用' : '停用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="锁定状态">
            <el-tag :type="warehouse.isQuitLocked ? 'info' : ''">
              {{ warehouse.isQuitLocked ? '锁定' : '未锁定' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="库位数量">
            <el-tag type="warning">{{ warehouse.zoneNumber || 0 }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 库区信息标签页 -->
      <div class="zones-section">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="仓位信息" name="zones">
            <div class="zone-toolbar">
              <el-input v-model="zoneSearch" placeholder="输入仓位名称/编号" style="width: 220px;" clearable />
              <div>
                <el-button type="primary" @click="searchZones">查询</el-button>
                <el-button @click="resetSearch">重置</el-button>
              </div>
            </div>

            <div class="zone-actions">
              <el-button @click="exportZones">导出</el-button>
              <el-button type="primary" :disabled="!selectedZones.length" @click="enableZones">启用</el-button>
              <el-button type="warning" :disabled="!selectedZones.length" @click="disableZones">停用</el-button>
            </div>

            <el-table 
              :data="filteredZones" 
              style="width: 100%" 
              @selection-change="handleZoneSelectionChange"
              border
            >
              <el-table-column type="selection" width="55" />
              <el-table-column label="序号" type="index" width="60" />
              <el-table-column prop="code" label="库位编号" width="150" />
              <el-table-column prop="name" label="库位名称" width="150" />
              <el-table-column prop="area" label="库位容量/m³" width="120" />
              <el-table-column prop="manager" label="库位主管" width="120" />
              <el-table-column prop="sortOrder" label="排序" width="80" />
              <el-table-column prop="status" label="库位状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                    {{ scope.row.status === 1 ? '启用' : '停用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="备注" min-width="150" />
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="操作记录" name="logs">
            <div class="empty-placeholder">
              <el-empty description="暂无操作记录" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const warehouseCode = ref(route.params.id);
const loading = ref(true);
const activeTab = ref('zones');
const zoneSearch = ref('');
const selectedZones = ref([]);

// 仓库信息
const warehouse = reactive({
  id: '',
  code: '',
  name: '',
  address: '',
  status: 1,
  contactPerson: '',
  contactPhone: '',
  area: 0,
  zoneNumber: 0,
  description: '',
  warehouseType: 0,
  manager: '',
  department: '',
  sortOrder: 0,
  isQuitLocked: false,
  zones: [],
  creator: '',
  createTime: '',
  updateTime: ''
});

// 库区列表
const zones = ref([]);

// 根据搜索过滤库区
const filteredZones = computed(() => {
  if (!zoneSearch.value) return zones.value;
  
  const searchTerm = zoneSearch.value.toLowerCase();
  return zones.value.filter(zone => 
    zone.code?.toLowerCase().includes(searchTerm) || 
    zone.name?.toLowerCase().includes(searchTerm)
  );
});

// 加载仓库详情
const loadWarehouseDetail = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`http://localhost:8080/api/app/ware-house-manage/by-code?code=${warehouseCode.value}`);
    const data = response.data;
    
    // 更新仓库信息
    Object.assign(warehouse, data);
    
    // 提取库区信息
    if (data.zones && Array.isArray(data.zones)) {
      zones.value = data.zones;
    }
    
  } catch (error) {
    console.error('获取仓库详情失败:', error);
    ElMessage.error('获取仓库详情失败');
  } finally {
    loading.value = false;
  }
};

// 处理库区选择变化
const handleZoneSelectionChange = (selection) => {
  selectedZones.value = selection;
};

// 搜索库区
const searchZones = () => {
  // 客户端过滤已经通过计算属性实现
  console.log('搜索关键词:', zoneSearch.value);
};

// 重置搜索
const resetSearch = () => {
  zoneSearch.value = '';
};

// 导出库区
const exportZones = () => {
  ElMessage.info('导出功能待实现');
};

// 启用选中库区
const enableZones = () => {
  if (selectedZones.value.length === 0) {
    ElMessage.warning('请选择要启用的库区');
    return;
  }
  
  ElMessageBox.confirm(`确认启用选中的${selectedZones.value.length}个库区?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实现批量启用逻辑
    ElMessage.success('批量启用成功');
    loadWarehouseDetail(); // 重新加载数据
  }).catch(() => {});
};

// 停用选中库区
const disableZones = () => {
  if (selectedZones.value.length === 0) {
    ElMessage.warning('请选择要停用的库区');
    return;
  }
  
  ElMessageBox.confirm(`确认停用选中的${selectedZones.value.length}个库区?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实现批量停用逻辑
    ElMessage.success('批量停用成功');
    loadWarehouseDetail(); // 重新加载数据
  }).catch(() => {});
};

// 编辑仓库
const handleEdit = () => {
  router.push(`/warehouse-edit/${warehouse.id}`);
};

// 删除仓库
const handleDelete = () => {
  ElMessageBox.confirm(`确认删除仓库 ${warehouse.name}?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实现删除逻辑
    ElMessage.success('删除成功');
    router.push('/warehouse');
  }).catch(() => {});
};

// 切换仓库状态
const toggleStatus = () => {
  const action = warehouse.status === 1 ? '停用' : '启用';
  
  ElMessageBox.confirm(`确认${action}仓库 ${warehouse.name}?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实现状态切换逻辑
    ElMessage.success(`${action}成功`);
    loadWarehouseDetail(); // 重新加载数据
  }).catch(() => {});
};

// 切换锁定状态
const toggleLock = () => {
  const action = warehouse.isQuitLocked ? '解锁' : '锁定';
  
  ElMessageBox.confirm(`确认${action}仓库 ${warehouse.name}?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实现锁定切换逻辑
    ElMessage.success(`${action}成功`);
    loadWarehouseDetail(); // 重新加载数据
  }).catch(() => {});
};

// 打印仓库信息
const handlePrint = () => {
  ElMessage.info('打印功能待实现');
};

// 页面加载时获取数据
onMounted(() => {
  if (warehouseCode.value) {
    loadWarehouseDetail();
  } else {
    ElMessage.error('未找到仓库编码');
    router.push('/warehouse');
  }
});
</script>

<style scoped>
.warehouse-detail {
  padding: 20px;
}

.detail-container {
  min-height: 400px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.detail-header h2 {
  font-size: 20px;
  margin: 0;
}

.action-buttons .el-button {
  margin-left: 8px;
}

.info-card {
  margin-bottom: 20px;
}

.zones-section {
  margin-top: 30px;
}

.zone-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.zone-actions {
  margin-bottom: 15px;
}

.empty-placeholder {
  padding: 40px 0;
}
</style>